//
//  LSAPIClient.m
//  LibraryStorm
//
//  Created by Enel@Lightning on 3/26/14.
//  Copyright (c) 2014 3ATeam. All rights reserved.
//

#import "LSAPIClient.h"

static NSString * const JSAPIBaseURLString = @"https://api.parse.com/1/";
static NSString * const kJSParseAPIApplicationId = @"08spxELwqPVTWhcu6Ux6JDV4ZWmfdu54urS7sBxG";
static NSString * const kJSParseAPIKey = @"plcDSsRxem3cPPgPxJTIJSgtN8nIl6eA3kJaAC7q";

@implementation LSAPIClient
/**
 * Method name: sharedClient
 * Description: Create object of LSAPIClient inheritance AFHTTPRequestOperationManager. Using create NSURLRequest to request server
 * Parameters: nil
 */
+ (instancetype)sharedClient
{
    static LSAPIClient *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[LSAPIClient alloc] initWithBaseURL:[NSURL URLWithString:JSAPIBaseURLString]];
    });
    
    return _sharedClient;
}

/**
 * Method name: initWithBaseURL
 * Description: Pass header value for api which it need validate.
 * Parameters: NSURL
 */
- (id)initWithBaseURL:(NSURL *)url
{
    self = [super initWithBaseURL:url];
    if (self) {
        [self.requestSerializer setValue:kJSParseAPIApplicationId forHTTPHeaderField:@"X-Parse-Application-Id"];
        [self.requestSerializer setValue:kJSParseAPIKey forHTTPHeaderField:@"X-Parse-REST-API-Key"];
        [self.operationQueue setMaxConcurrentOperationCount:3];
    }
    
    return self;
}

/**
 * Method name: GETRequestForClass:parameters
 * Description: Create NSURLRequest which method GET. Base method which using for other method.
 * Parameters: NSString className, NSDictionary parameters
 */
- (NSMutableURLRequest *)GETRequestForClass:(NSString *)className parameters:(NSDictionary *)parameters {
    NSMutableURLRequest *request = nil;
    NSError *error = NULL;
    request = [self.requestSerializer requestWithMethod:@"GET" URLString:[NSString stringWithFormat:@"%@classes/%@", [self.baseURL absoluteString] ,className] parameters:parameters error:&error];
    request.timeoutInterval = TIMEOUT_INTERVAL;
    if (error) {
        NSLog(@"%@", error.localizedDescription);
        return nil;
    }
    
    return request;
}

- (NSMutableURLRequest *)GETRequestForAllRecordsOfClass:(NSString *)className updatedAfterDate:(NSDate *)updatedDate limitRecords:(int)limit skipOverRecords:(int)skip
{
    NSMutableURLRequest *request = nil;
    NSMutableDictionary *paramters = [NSMutableDictionary dictionary];
    if (updatedDate) {
        [[kAppDelegate dateFormatter] setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.'999Z'"];
        [[kAppDelegate dateFormatter] setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
        
        NSString *jsonString = [NSString
                                stringWithFormat:@"{\"updatedAt\":{\"$gte\":{\"__type\":\"Date\",\"iso\":\"%@\"}}}",
                                [[kAppDelegate dateFormatter] stringFromDate:updatedDate]];
        
        [paramters setObject:jsonString forKey:@"where"];
    }
    
    if (limit > 0) {
        [paramters setObject:[NSNumber numberWithInt:limit] forKey:@"limit"];
    }
    
    if (skip > 0) {
        [paramters setObject:[NSNumber numberWithInt:skip] forKey:@"skip"];
    }
    
    // Get records sort by id
    if ([className isEqualToString:BOOK_DETAIL]) {
        [paramters setObject:@"-bookId" forKey:@"order"];
    }else if ([className isEqualToString:BOOK_CATEGORY]) {
        [paramters setObject:@"categoryId" forKey:@"order"];
    }
    
    request = [self GETRequestForClass:className parameters:paramters];
    return request;
}

- (NSMutableURLRequest *)GETRequestForAllRecordsOfClass:(NSString *)className updatedAfterDate:(NSDate *)updatedDate categoryType:(int)categoryId limitRecords:(int)limit skipOverRecords:(int)skip
{
    NSMutableURLRequest *request = nil;
    NSMutableDictionary *paramters = [NSMutableDictionary dictionary];
    if (updatedDate) {
        [[kAppDelegate dateFormatter] setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.'999Z'"];
        [[kAppDelegate dateFormatter] setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
        
        NSString *jsonString = [NSString
                                stringWithFormat:@"{\"updatedAt\":{\"$gte\":{\"__type\":\"Date\",\"iso\":\"%@\"}}}",
                                [[kAppDelegate dateFormatter] stringFromDate:updatedDate]];
        
        [paramters setObject:jsonString forKey:@"where"];
    }
    
    if (categoryId > 0 && [className isEqualToString:@"BookDetail"]) {
        NSString *updatedAtJSONString = [paramters objectForKey:@"where"];
        NSString *subJSONString = (NSMutableString *)[updatedAtJSONString substringToIndex:[updatedAtJSONString length] - 1];
        NSString *categoryJSONString = nil;
        if (subJSONString && subJSONString.length > 0) {
            categoryJSONString = [NSString stringWithFormat:@"%@ , \"categoryIds\":\"%d\"}", subJSONString, categoryId];
        }else {
            categoryJSONString = [NSString stringWithFormat:@"{\"categoryIds\":\"%d\"}", categoryId];
        }
        
        [paramters setObject:categoryJSONString forKey:@"where"];
    }
    
    if (limit > 0) {
        [paramters setObject:[NSNumber numberWithInt:limit] forKey:@"limit"];
    }
    
    if (skip > 0) {
        [paramters setObject:[NSNumber numberWithInt:skip] forKey:@"skip"];
    }
    
    // Get records sort by id
    if ([className isEqualToString:BOOK_DETAIL]) {
        [paramters setObject:@"-bookId" forKey:@"order"];
    }else if ([className isEqualToString:BOOK_CATEGORY]) {
        [paramters setObject:@"categoryId" forKey:@"order"];
    }
    
    request = [self GETRequestForClass:className parameters:paramters];
    return request;
}

/**
 * Method name: GETRequestForPushNotificationWithDeviceToken:
 * Description: Create NSURLRequest which method GET. Register APNS to parse service.
 * Parameters: NSString deviceToken
 */
- (NSMutableURLRequest *)POSTRequestForPushNotificationWithDeviceToken:(NSString *)deviceToken
{
    NSMutableURLRequest *request = nil;
    NSError *error = NULL;
    NSDictionary *parameters = @{@"deviceType":@"iOS", @"deviceToken":deviceToken, @"channels":@[@"BookStorm"]};
    request = [self.requestSerializer requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@installations", [self.baseURL absoluteString]] parameters:parameters error:&error];
    request.timeoutInterval = TIMEOUT_INTERVAL;
    if (error) {
        NSLog(@"%@", error.localizedDescription);
        return nil;
    }
    
    return request;
}
@end
